<template>
  <div style="background: white;">
    <div class="title" >
      <div style="flex: 1;">
        商品入库（扫描入库单）
      </div>
    </div>
    <div  class="order" style="background: white;">
      <j-grid v-model="state.orders" :columns="cols" :offset-width="105" show-footer :offset-bottom="100"> </j-grid>
      <div style="text-align: center;margin-top: 20px;background: white;height: 100px;display: flex;">
<!--        <div style="text-align: center;padding-left: 50px;">-->
<!--          <tiny-radio-group v-model="ck" type="button" :options="burronOptions"></tiny-radio-group>-->
<!--        </div>-->
        <div style="flex: 1;">
          <j-button type="info" size="large" @click="saveRk">保存入库</j-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
// 订单分配
import tool from "@/utils/tool";
import {computed, onBeforeMount, onMounted, ref} from "vue";
const gridHeight = ref(300)
const state = ref({
  orders: [],
  deliverModal: false,
  showModal: false,
  showcargo: false,
  title: '',
  today: tool.getDay(),
  testVal: '',
  tempOrders: [],
  drivers: [],
  deliverNames: '',
  user: {},
  showRet: false,
  sets: {},
  ocrJson: []
})
const cols = ref([
  {type:'index', width: 60},
  {field: 'billNo', title: '票号', width: 130},
  {field: 'billDate', title: '票据日期', width: 100},
  {field: 'buName', title: '供应商', width: 100},
  {field: 'invName', title: '商品名称' },
  {field: 'spec', title: '规格', width: 70},
  {field: 'price', title: '单价', width: 70,align:'right'},
  {field: 'qty', title: '数量', width: 70,align:'right', sum: true},
  {field: 'amount', title: '金额', width: 90,align:'right', sum: true},
  {field: '', title: '操作', width: 70,btns:[{label:'删除',click:(row) => {
        delRow(row)
      }}]},
])
onBeforeMount(() => {
  state.value.user = tool.data.getUser()
})
const ck = ref('')
const uuid = ref('')
const burronOptions = ref([])
onMounted(() => {
  window.ocr = doOcr
  gridHeight.value = window.innerHeight - 150
  if(wrapRef.value) {
    let rec = wrapRef.value.getBoundingClientRect()
    tbWidth.value = rec.width
  }
  tool.post('justdeliver/getCkList').then(ret => {
    if(ret.stat) {
      burronOptions.value = ret.data
      if(ret.data.length > 0) {
        ck.value = ret.data[0].label
      }
    }
  })

})
const tbWidth = ref(800)
const wrapRef = ref(null)
const saveRk = () => {
  if(state.value.orders.length === 0) return tool.err('没有数据')
  tool.confirm('保存入库？').ther(() => {
    tool.post('justdeliver/saveRk', {uuid:uuid.value }, true).then(ret => {
      if(ret.stat) {
        uuid.value = ''
        state.value.orders = []
      }
    })
  })
}
const delRow = (row) => {
  let billNo = row.billNo
  for (let i = 0; i < state.value.orders.length; i++) {
    if(state.value.orders[i].billNo === billNo) {
      state.value.orders.splice(i, 1)
      if(state.value.orders.length === 0) uuid.value = ''
      break
    }
  }
}

const doOcr = (params) => {
  let tables = params.tables
  try {
    let bill = {
      headInfo: [],
      infos: []
    }
    for (let i = 0; i < tables.length; i++) {
      let item = tables[i]
      if (item.type === "plain") {
        if (item.lines.length > 0) {
          for (let j = 0; j < item.lines.length; j++) {
            let line = item.lines[j]
            if (line.score > 0.91) {
              let txt = tool.xe.trim(line.text)
              bill.headInfo.push(txt)
            }
          }
        }
      }
      if (item.type === "table_with_line") {
        let infos = []
        let rows = item['table_rows']
        let cols = item['table_cols']
        if (rows > 0 && cols > 0 && item['table_cells']) {
          let info = {}
          let tb_header = []
          for (let j = 0; j < item['table_cells'].length; j++) {
            let cell = item['table_cells'][j]
            let start_row = cell['start_row']
            let start_col = cell['start_col']
            let end_col = cell['end_col']
            if (start_row === 0) {
              if (cell.text)
                tb_header.push({col: {start: start_col, end: end_col}, txt: tool.xe.trim(cell.text)})
            } else {
              break
            }
          }
          for (let j = 0; j < item['table_cells'].length; j++) {
            let cell = item['table_cells'][j]
            let start_row = cell['start_row']
            let start_col = cell['start_col']
            let end_col = cell['end_col']
            if (start_row > 0) {
              if(start_row !== item['table_cells'][j-1].start_row && start_col === 0) {
                if(!tool.xe.isEmpty(info)) infos.push(tool.xe.clone(info, true))
              }
              if(cell.text.indexOf('合计') !== -1 || cell.text.indexOf('总计') !== -1 ) break
              for (let k = 0; k < tb_header.length; k++) {
                if(start_col===tb_header[k].col.start && end_col ===tb_header[k].col.end) {
                  info[tb_header[k].txt] = tool.xe.trim(cell.text)
                }
              }
            }
          }
        }
        bill.infos = infos
        break
      }
    }
    if(bill.infos.length === 0) {
      return tool.err('没有商品信息')
    }
    if(!uuid.value) uuid.value = tool.uuid()
    tool.post('justdeliver/gpRkList', {formData: bill, uuid:uuid.value }).then(ret => {
      if(ret.stat) {
        state.value.orders = ret.data.orders
        playAudio('suc')
      }
      else {
        if(ret.msg.indexOf('已配送') !== -1) {
          playAudio('yps')
        }
        else if(ret.msg.indexOf('合计失败') !== -1) {
          playAudio('sbsb')
        }
        else {
          playAudio('err')
        }
        return tool.err(ret.msg)
      }
    })
  }
  catch (e) {
    return []
  }
}

const playAudio = (str) => {
  // tool.sendToPy({name: 'play', sound: str})
  // 创建AudioContext
  const audioContext = new (window.AudioContext || window.webkitAudioContext)();
  // 加载音频文件
  fetch('/audio/' + str + '.wav')
      .then(response => response.arrayBuffer())
      .then(arrayBuffer => audioContext.decodeAudioData(arrayBuffer))
      .then(audioBuffer => {
        // 创建音频源节点
        const source = audioContext.createBufferSource();
        source.buffer = audioBuffer;
        // 连接到输出
        source.connect(audioContext.destination);
        // 播放
        source.start();
      })
      .catch(e => console.error('Error with decoding audio data', e));
}

</script>

<style scoped lang="scss">


.title {
  text-align: center;
  font-weight: bold;
  font-size: 22px;
  background-color: #01aaee;
  color: white;
  height: 40px;
  line-height: 40px;
  display: flex;
}

.s-item {
  border-bottom: 1px solid #F2F2F2;
  padding: 5px 0;
  margin-bottom: 10px;
}


.undeliver tr:hover {
  background-color: #f8f8f9;
}

.pd2 {
  padding: 2px;
}

.grid td {
  padding-left: 2px;
}

.order {
  padding-top: 2px;
}

.br {
  border-right: 1px solid #dedede;
}

.order .grid td {
  /*background-color: white;*/
}

.bb {
  border-bottom: 1px solid #dedede;
}

.bt {
  border-top: 1px solid #dedede;
}

.bl {
  border-left: 1px solid #dedede;
}

.tc {
  text-align: center;
}

.tr {
  text-align: right;
}

.order td, .order th {
  height: 30px;
  line-height: 30px;
}

.order td {
  color: #2b85e4;
}

.order .grid tr {
  /*background-color: white;*/
}

.order .grid tr:hover {
  background-color: gainsboro;
}

.grid tr {
  /*background-color: white;*/
}

.order td i {

}

.order td i:hover {
  cursor: pointer;
  color: red;
}

.undeliver {
}

.undeliver th {
  padding: 5px 3px;
}

.undeliver td {
  padding: 5px 3px;
}

li {
  margin-top: 10px;
}
.ocr {
  td {
    border: 1px solid #01aaee;
  }
  th {
    border: 1px solid #01aaee;
  }
}

.orow:hover, .orow:active {
  background-color: #2db7f5;
  color: white;
}
</style>